<?php
namespace console\controllers;
use common\bonus\BaseBonus;
use common\models\Balance;
use common\models\BalanceLog;
use common\models\EthTradeLog;
use common\models\Member;
use common\models\StaticInstance;
use common\models\TradeClub;
use common\models\TradeCommodity;
use common\models\TradeModel;
use common\utils\CommonFun;

class TradeClubController extends CoreController{
    public function actionIndex()
    {
        $where = ['status'=>'1','order_type'=>4];
        /*判断剩余总数*/
        $data = StaticInstance::find()->where($where)->andWhere(['>','remain_num',0])->asarray()->all();

        if(!$data) return false;

        $conf = TradeModel::getStaticReleaseConf('StaticRelease');

        ## 帐本分配方式
        $assignType = json_decode($conf['assign_type'],1);

        $st = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $memberId = array_unique(array_column($data,'commodity_id'));
        /**/
        $commodityInfo = TradeClub::getAll(['commodity_id'=>$memberId],'day_income,commodity_id');
        $commodity     = [];

        foreach ($commodityInfo as $gk=>$gv) {
            $commodity[$gv['commodity_id']]=$gv['day_income'];
        }
        /*每天分1000*/

        $st1    = strtotime(date("Y-m-d 00:00:00",strtotime("-1 day")));
        $et    = strtotime(date("Y-m-d 23:59:59",strtotime("-1 day")));
        $today_recharge = EthTradeLog::find()->where(['between', 'create_time', $st1, $et])->sum('value');

        if ($today_recharge) {
            $recharge = round(($today_recharge * 0.001) / 100, 2);
            $data1 = StaticInstance::find()->where($where)->andWhere(['>', 'remain_num', 0])->asarray()->all();
            if ($data1) {
                $userArr = array_unique(array_column($data1, 'member_id'));
                $userCount = count($userArr);
                $money = 0;
                if ($recharge) {
                    $money = $recharge / $userCount;
                }
                if($money) {
                    foreach ($userArr as $k => $v) {
                        //加入到账本
                        $res = Balance::addBalance($v, 3, $money, 19, 1);
                    }
                }
            }
        }

        foreach($data as $val)
        {

            $where = ['member_id'=>$val['member_id'],'source_id'=>$val['id'],'source_type'=>8];


            /*求出每天释放的金额数量*/
            $bonus= bcmul($val['total_num'],$commodity[$val['commodity_id']],4)/100;

            if($bonus<=0) continue;
            //封顶值
            if($conf['max_times']>0 && $val['was_num']>=$val['in_num']*$conf['max_times']) continue;


            ## 更新实例
            $bonus = $this->updateInstance($val,$bonus);

            foreach($assignType as $btype=>$rate)
            {
                $balance = round($bonus * $rate / 100 , 2);
                //加入到账本
                $res = Balance::addBalance($val['member_id'],$btype,$balance,19,$val['id']);

                if(!$res['state']){
                    $str = '静态释放 instance_id:'.$val['id']."\r\n conf:".json_encode($conf).'msg:'.$res['msg'];
                    CommonFun::writeLog($str,'bonus');
                }
            }

            if($val['bonus_day']==$val['period_day']){
                $res = Balance::addBalance($val['member_id'],1,$val['in_num'],16,$val['id']);
                if(!$res['state']){
                    $str = '增加合同本金失败';
                    CommonFun::writeLog($str);
                }
                $res = Balance::reduceBalance($val['member_id'],3,$val['in_num'],16,$val['id']);
                if(!$res['state']){
                    $str = '释放合同金额失败';
                    CommonFun::writeLog($str);
                }
            }
        }
        return true;
    }

    //更新实例
    private function updateInstance($instance,$bonus)
    {
        //因为实例数据已经变化了，需要重新获取，不然会覆盖
        $instance = StaticInstance::find()->where(["id"=>$instance['id']])->andWhere(['>','remain_num',0])->asarray()->one();
        if(!$instance) return false;

        $bonus = min($instance['remain_num'],$bonus);

        $data = array();
        /*已经释放的钱*/
        $data['was_num'] = $instance['was_num'] + $bonus;
        /*释放+1天*/
        $data['bonus_day'] = $instance['bonus_day'] + 1;
        /*剩余总数-当前价格*/
        $data['remain_num'] = $instance['remain_num'] - $bonus;
        $data['update_time'] = time();
        if($instance['period_day']-$data['bonus_day']<=0) $data['status'] = '2';

        $flag =  StaticInstance::updateAll($data,['id'=>$instance['id']]);
        if(!$flag){
            echo "实例更新失败，id:".$instance['id']."\r\n";
            return false;
        }
        return $bonus;
    }
}